const api = require('../../utils/api.js')

Page({
  data: {
    adminId: null,
    admin: {
      username: '',
      nickname: '',
      password: '',
      status: 1,
      permissions: {}
    },
    showPassword: false,
    permissionModules: [
      { key: 'product_manage', name: '产品管理' },
      { key: 'model_manage', name: '型号管理' },
      { key: 'process_manage', name: '工序管理' },
      { key: 'price_manage', name: '价格管理' },
      { key: 'order_manage', name: '订单管理' },
      { key: 'allocation_manage', name: '分工管理' },
      { key: 'report_manage', name: '报工管理' },
      { key: 'active_report_manage', name: '主动报工管理' },
      { key: 'production_plan_manage', name: '生产计划管理' },
      { key: 'admin_manage', name: '管理员管理' }
    ],
    permissionActions: [
      { key: 'view', name: '查看' },
      { key: 'add', name: '新增' },
      { key: 'edit', name: '编辑' },
      { key: 'delete', name: '删除' },
      { key: 'batch', name: '批量操作' },
      { key: 'audit', name: '审核' }
    ]
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        adminId: options.id
      })
      this.loadAdminData(options.id)
    }
  },

  // 加载管理员数据
  async loadAdminData(adminId) {
    try {
      wx.showLoading({
        title: '加载中...'
      })
      
      const app = getApp()
      const globalData = app ? app.globalData : { token: '', baseUrl: '' }
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: globalData.baseUrl + '/getAdminDetail',
          method: 'GET',
          data: { id: adminId },
          header: {
            'content-type': 'application/json',
            'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res.data)
            } else {
              reject(res)
            }
          },
          fail: reject
        })
      })
      
      wx.hideLoading()
      
      if (res.code === 1) {
        console.log('获取到的管理员数据:', res.data)
        console.log('获取到的管理员权限数据:', res.data.rule_list)
        
        // 从rule_list解析权限数据
        let permissions = {}
        if (res.data.rule_list && Array.isArray(res.data.rule_list)) {
          // 将rule_list转换为permissions对象格式
          res.data.rule_list.forEach(rule => {
            const parts = rule.split('/')
            if (parts.length === 2) {
              const module = parts[0]
              const action = parts[1]
              
              if (!permissions[module]) {
                permissions[module] = []
              }
              if (!permissions[module].includes(action)) {
                permissions[module].push(action)
              }
            }
          })
        }
        
        console.log('解析后的权限数据:', permissions)
        
        // 详细调试信息
        console.log('=== 权限解析详情 ===')
        Object.keys(permissions).forEach(module => {
          console.log(`模块 ${module}:`, permissions[module])
        })
        
        // 如果权限数据为空，使用默认权限
        if (!permissions || Object.keys(permissions).length === 0) {
          console.log('权限数据无效，使用默认权限')
          permissions = this.getDefaultPermissions()
        }
        
        // 确保每个模块都有权限数组（但不要覆盖已解析的权限）
        this.data.permissionModules.forEach(module => {
          if (!permissions[module.key] || !Array.isArray(permissions[module.key])) {
            // price_manage 模块不给任何默认权限
            if (module.key === 'price_manage') {
              console.log(`模块 ${module.key} 权限缺失，但不给默认权限`)
              permissions[module.key] = []
            } else {
              console.log(`模块 ${module.key} 权限缺失，设置为默认view权限`)
              permissions[module.key] = ['view']
            }
          } else {
            console.log(`模块 ${module.key} 权限:`, permissions[module.key])
          }
        })
        
        console.log('最终权限配置:', permissions)
        console.log('权限模块列表:', this.data.permissionModules)
        
        const admin = {
          id: res.data.id,
          username: res.data.username,
          nickname: res.data.nickname,
          password: '',
          status: parseInt(res.data.status) || 1,
          permissions: permissions
        }
        
        console.log('准备设置的管理员数据:', admin)
        console.log('admin.permissions 详细内容:', admin.permissions)
        
        this.setData({
          admin: admin
        })
        
        // 立即验证setData后的数据
        setTimeout(() => {
          console.log('setData后立即检查 - admin.permissions:', this.data.admin.permissions)
          console.log('setData后立即检查 - product_manage权限:', this.data.admin.permissions.product_manage)
        }, 100)
        
        // 强制刷新权限显示
        this.forceUpdatePermissions()
        
        // 验证权限数据是否正确设置
        setTimeout(() => {
          console.log('=== 权限数据验证 ===')
          console.log('setData后的admin:', this.data.admin)
          console.log('setData后的permissions:', this.data.admin.permissions)
          
          // 测试几个权限检查
          this.data.permissionModules.forEach(module => {
            const modulePermissions = this.data.admin.permissions[module.key] || []
            console.log(`模块 ${module.key} 权限:`, modulePermissions)
            
            this.data.permissionActions.forEach(action => {
              const isSelected = this.data.admin.permissions[module.key] && 
                               this.data.admin.permissions[module.key].indexOf(action.key) > -1
              console.log(`  ${action.key}: ${isSelected}`)
            })
          })
        }, 100)
      } else {
        wx.showToast({
          title: res.msg || '获取管理员信息失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('获取管理员详情失败:', error)
      wx.showToast({
        title: '获取管理员信息失败',
        icon: 'none'
      })
    }
  },

  // 获取默认权限配置
  getDefaultPermissions() {
    const permissions = {}
    this.data.permissionModules.forEach(module => {
      // price_manage 模块不给任何默认权限
      if (module.key === 'price_manage') {
        permissions[module.key] = []
      } else {
        permissions[module.key] = ['view'] // 默认只有查看权限
      }
    })
    console.log('默认权限配置:', permissions)
    return permissions
  },

  // 输入框变化处理
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    
    this.setData({
      [`admin.${field}`]: value
    })
  },

  // 状态选择器变化处理
  onStatusPickerChange(e) {
    this.setData({
      'admin.status': parseInt(e.detail.value)
    })
  },

  // 切换密码显示/隐藏
  togglePasswordVisibility() {
    this.setData({
      showPassword: !this.data.showPassword
    })
  },

  // 权限选择处理
  onPermissionChange(e) {
    const { module, action } = e.currentTarget.dataset
    const permissions = { ...this.data.admin.permissions }
    
    // 确保模块权限数组存在
    if (!permissions[module] || !Array.isArray(permissions[module])) {
      permissions[module] = []
    }
    
    const index = permissions[module].indexOf(action)
    if (index > -1) {
      permissions[module].splice(index, 1)
    } else {
      permissions[module].push(action)
    }
    
    // 确保view权限始终存在
    if (permissions[module].length > 0 && !permissions[module].includes('view')) {
      permissions[module].unshift('view')
    }
    
    console.log(`权限变更 ${module}.${action}:`, {
      module,
      action,
      newPermissions: permissions[module],
      allPermissions: permissions
    })
    
    this.setData({
      'admin.permissions': permissions
    })
  },

  // 检查权限是否被选中
  isPermissionSelected(module, action) {
    const permissions = this.data.admin.permissions || {}
    const modulePermissions = permissions[module] || []
    return Array.isArray(modulePermissions) && modulePermissions.includes(action)
  },

  // 测试权限数据
  testPermissions() {
    console.log('=== 测试权限数据 ===')
    console.log('当前admin数据:', this.data.admin)
    console.log('当前permissions数据:', this.data.admin?.permissions)
    
    if (this.data.admin && this.data.admin.permissions) {
      this.data.permissionModules.forEach(module => {
        const modulePermissions = this.data.admin.permissions[module.key] || []
        console.log(`模块 ${module.key}:`, modulePermissions)
        
        this.data.permissionActions.forEach(action => {
          const isSelected = this.data.admin.permissions[module.key] && 
                           this.data.admin.permissions[module.key].indexOf(action.key) > -1
          console.log(`  ${action.key}: ${isSelected}`)
        })
      })
      
      wx.showToast({
        title: '权限数据已输出到控制台',
        icon: 'none'
      })
    } else {
      wx.showToast({
        title: '权限数据不存在',
        icon: 'none'
      })
    }
  },

  // 强制刷新权限显示
  forceUpdatePermissions() {
    console.log('强制刷新权限显示')
    console.log('当前admin.permissions:', this.data.admin.permissions)
    // 触发一次setData来强制刷新视图
    this.setData({
      'admin.permissions': this.data.admin.permissions
    })
  },
  
  // 测试权限数据
  testPermissionData() {
    console.log('=== 测试权限数据 ===')
    console.log('this.data.admin:', this.data.admin)
    console.log('this.data.admin.permissions:', this.data.admin.permissions)
    
    if (this.data.admin.permissions) {
      Object.keys(this.data.admin.permissions).forEach(module => {
        console.log(`模块 ${module} 权限:`, this.data.admin.permissions[module])
      })
    }
    
    // 测试特定模块的权限检查
    const productManage = this.data.admin.permissions.product_manage
    console.log('product_manage权限:', productManage)
    console.log('product_manage是否包含view:', productManage && productManage.indexOf('view') > -1)
    console.log('product_manage是否包含add:', productManage && productManage.indexOf('add') > -1)
  },

  // 获取权限动作的详细说明
  getActionDescription(actionKey) {
    const descriptions = {
      'view': '查看数据',
      'add': '创建数据',
      'edit': '修改数据',
      'delete': '删除数据',
      'batch': '批量处理',
      'audit': '审核数据'
    }
    return descriptions[actionKey] || '未知权限'
  },

  // 获取权限的中文名称
  getActionChineseName(actionKey) {
    const chineseNames = {
      'view': '查看',
      'add': '新增',
      'edit': '编辑',
      'delete': '删除',
      'batch': '批量操作',
      'audit': '审核'
    }
    return chineseNames[actionKey] || actionKey
  },

  // 获取模块当前权限的中文显示
  getModulePermissionsText(moduleKey) {
    console.log(`=== getModulePermissionsText 调用 ===`)
    console.log('moduleKey:', moduleKey)
    console.log('this.data.admin:', this.data.admin)
    console.log('this.data.admin.permissions:', this.data.admin.permissions)
    
    const permissions = this.data.admin.permissions || {}
    const modulePermissions = permissions[moduleKey] || []
    
    console.log('permissions:', permissions)
    console.log('modulePermissions:', modulePermissions)
    
    if (modulePermissions.length === 0) {
      console.log('返回: 无权限')
      return '无权限'
    }
    
    // 将权限代码转换为中文名称
    const chinesePermissions = modulePermissions.map(action => this.getActionChineseName(action))
    console.log('chinesePermissions:', chinesePermissions)
    const result = chinesePermissions.join('、')
    console.log('最终结果:', result)
    return result
  },

  // 保存管理员
  async onSave() {
    const admin = this.data.admin
    
    // 验证必填字段
    if (!admin.nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }
    
    // 确保每个模块至少包含view权限（除了price_manage）
    if (admin.permissions) {
      this.data.permissionModules.forEach(module => {
        // price_manage 模块不强制添加查看权限
        if (module.key === 'price_manage') {
          // 如果权限为空，保持为空数组
          if (!admin.permissions[module.key] || !Array.isArray(admin.permissions[module.key])) {
            admin.permissions[module.key] = []
          }
        } else {
          // 其他模块确保至少包含view权限
          if (!admin.permissions[module.key] || admin.permissions[module.key].length === 0) {
            admin.permissions[module.key] = ['view']
          } else if (!admin.permissions[module.key].includes('view')) {
            admin.permissions[module.key].unshift('view')
          }
        }
      })
    }
    
    try {
      wx.showLoading({
        title: '保存中...'
      })
      
      const app = getApp()
      const globalData = app ? app.globalData : { token: '', baseUrl: '' }
      
      // 先更新管理员基本信息
      const basicInfo = {
        id: admin.id,
        username: admin.username,
        nickname: admin.nickname,
        status: admin.status
      }
      
      // 如果有密码，添加到更新数据中
      if (admin.password && admin.password.trim()) {
        basicInfo.password = admin.password
      }
      
      const result = await new Promise((resolve, reject) => {
        wx.request({
          url: globalData.baseUrl + '/updateAdmin',
          method: 'POST',
          data: basicInfo,
          header: {
            'content-type': 'application/json',
            'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res.data)
            } else {
              reject(res)
            }
          },
          fail: reject
        })
      })
      
      if (result.code === 1) {
        // 基本信息更新成功，现在更新权限
        console.log('管理员基本信息更新成功，开始更新权限')
        console.log('权限数据:', admin.permissions)
        
        // 将权限数据转换为新权限系统格式
        const permissions = []
        if (admin.permissions) {
          Object.keys(admin.permissions).forEach(module => {
            const actions = admin.permissions[module]
            if (Array.isArray(actions)) {
              actions.forEach(action => {
                permissions.push(`${module}/${action}`)
              })
            }
          })
        }
        
        console.log('转换后的权限列表:', permissions)
        
        // 调用新的权限设置API
        const permissionResult = await new Promise((resolve, reject) => {
          wx.request({
            url: globalData.baseUrl + '/setAdminPermissions',
            method: 'POST',
            data: {
              admin_id: admin.id,
              permissions: permissions
            },
            header: {
              'content-type': 'application/json',
              'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
            },
            success: (res) => {
              if (res.statusCode === 200) {
                resolve(res.data)
              } else {
                reject(res)
              }
            },
            fail: reject
          })
        })
        
        wx.hideLoading()
        
        if (permissionResult.code === 1) {
          wx.showToast({
            title: '更新成功',
            icon: 'success'
          })
          
          // 返回上一页并刷新数据
          setTimeout(() => {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if (prevPage && prevPage.loadData) {
              prevPage.loadData()
            }
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: permissionResult.msg || '权限更新失败',
            icon: 'none'
          })
        }
      } else {
        wx.hideLoading()
        wx.showToast({
          title: result.msg || '更新失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('更新管理员失败:', error)
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      })
    }
  },

  // 返回上一页
  onBack() {
    wx.navigateBack()
  }
})
